package net.kazed.nextaction.task;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.regex.Pattern;

import net.kazed.android.inject.Autowired;
import net.kazed.android.inject.InjectedActivity;
import net.kazed.nextaction.ApplicationResource;
import net.kazed.nextaction.NextActionApplication;
import net.kazed.nextaction.R;
import net.kazed.nextaction.database.ContextCache;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;
import net.kazed.nextaction.database.TaskContext;
import net.kazed.nextaction.database.TaskDao;
import net.kazed.nextaction.database.TaskStatus;
import net.kazed.nextaction.database.TreeNode;
import net.kazed.nextaction.timer.TimerDialog;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.util.Linkify;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TaskViewActivity extends InjectedActivity {

    private static final String TAG = "TaskViewActivity";
    
    private static final int MENU_EDIT = Menu.FIRST;
    private static final int MENU_DELETE = MENU_EDIT + 1;
    private static final int MENU_MARK_COMPLETED = MENU_DELETE + 1;
    private static final int MENU_TIMER = MENU_MARK_COMPLETED + 1;
   
    private static final int DIALOG_TIMER = 0;
    
    private static final int ACTIVITY_EDIT_ACTION = 0;

    private TaskAttachmentManager taskAttachmentManager;
    private TaskDao taskDao;
    private ContextCache contextCache;

    private DateFormat dateFormat;
    private String noDateLabel;
    private Cursor cursor;
    private Uri itemUri;
    
    private Task originalTask;
    private Task parentTask;
    
    private TextView parentDescription;
    private TextView nameWidget;
    private LinearLayout taskContextContainer;
    private TextView typeText;
    private TextView statusText;
    private TextView startDateText;
    private TextView dueDateText;
    private TextView noteWidget;
    private ApplicationResource applicationResource;
        
    @Autowired
    public void setTaskAttachmentManager(TaskAttachmentManager taskAttachmentManager) {
      this.taskAttachmentManager = taskAttachmentManager;
    }

    @Autowired
    public void setTaskDao(TaskDao taskDao) {
       this.taskDao = taskDao;
    }
    
    @Autowired
    public void setContextCache(ContextCache contextCache) {
       this.contextCache = contextCache;
    }
    
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Resources resources = getResources();
        noDateLabel = resources.getString(R.string.no_date_set);

        final Intent intent = getIntent();
        itemUri = intent.getData();
        
        setContentView(R.layout.task_view);
        parentDescription = (TextView) findViewById(R.id.parent_description);
        nameWidget = (TextView) findViewById(R.id.description);
        taskContextContainer = (LinearLayout) findViewById(R.id.task_contexts);
        typeText = (TextView) findViewById(R.id.type);
        statusText = (TextView) findViewById(R.id.status);
        startDateText = (TextView) findViewById(R.id.start_date_display);
        dueDateText = (TextView) findViewById(R.id.due_date_display);
        noteWidget = (TextView) findViewById(R.id.notes);

        NextActionApplication application = (NextActionApplication) getApplication();
        applicationResource = application.getApplicationResource();
    }
    
    @Override
    protected void onResume() {
        super.onResume();

        cursor = managedQuery(itemUri, Task.FULL_PROJECTION.getFieldNames(), null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            originalTask = new Task(cursor);
            populateFields(originalTask);
        }
    }

   @Override
   protected void onPause() {
      super.onPause();
      Intent intent = new Intent(Intent.ACTION_VIEW, itemUri);
      setResult(RESULT_OK, intent);
   }

   /**
    * Populate UI components with data from task.
    * @param task Current task.
    */
   private void populateFields(Task task) {
      if (task.getParentTaskId() != null) {
          Uri parentItem = ContentUris.withAppendedId(Task.CONTENT_URI, task.getParentTaskId());
          Cursor parentCursor = managedQuery(parentItem, Task.FULL_PROJECTION.getFieldNames(), null, null, null);
          if (parentCursor.moveToFirst()) {
              parentTask = new Task(parentCursor);
          }
          parentCursor.close();
      }
      if (parentTask != null) {
          parentDescription.setText(parentTask.getDescription());
      }
      nameWidget.setText(task.getDescription() == null ? "" : task.getDescription());
      String status = null;
      if (task.getComplete()) {
         status = getResources().getString(R.string.status_completed);
      } else {
         status = getResources().getString(R.string.status_in_progress);
      }
      TaskStatus type = task.getStatus(TaskStatus.UNPROCESSED);
      typeText.setText(getResources().getString(applicationResource.getTaskTypeName(type)));
      statusText.setText(status);
      if (task.getStartDate() == null) {
          startDateText.setTextKeepState(noDateLabel);
      } else {
          startDateText.setTextKeepState(dateFormat.format(task.getStartDate()));
      }
      if (task.getDueDate() == null) {
          dueDateText.setTextKeepState(noDateLabel);
      } else {
          dueDateText.setTextKeepState(dateFormat.format(task.getDueDate()));
      }
      noteWidget.setText(task.getDetails());
      Pattern wikiWordMatcher = Pattern.compile("\\b[A-Z]+[a-z0-9]+[A-Z][A-Za-z0-9]+\\b");
      String wikiViewURL =    "content://com.google.android.wikinotes.db.wikinotes/wikinotes/";
      Linkify.addLinks(noteWidget, wikiWordMatcher, wikiViewURL);
      
      for (AttachmentType attachmentType : taskAttachmentManager.getAttachmentTypes()) {
          attachmentType.addLinks(noteWidget);
      }
    
      LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      List<TaskContext> taskContexts = taskDao.getTaskContexts(task.getId());
      taskContextContainer.removeAllViews();
      if (taskContexts.isEmpty()) {
         View contextView = vi.inflate(R.layout.task_context_list_item_view, taskContextContainer, false); 
         TextView contextNameView = (TextView) contextView.findViewById(R.id.name);
         contextNameView.setText(R.string.no_contexts_in_view);
         taskContextContainer.addView(contextView);
      } else {
         for (TaskContext taskContext : taskContexts) {
            TreeNode<GtdContext> treeNode = contextCache.getContextTree(taskContext.getContextId());
            ContextCache.ContextPathBuilder pathBuilder = new ContextCache.ContextPathBuilder("/");
            treeNode.fillContextPath(pathBuilder);
            View contextView = vi.inflate(R.layout.task_context_list_item_view, taskContextContainer, false); 
            TextView contextNameView = (TextView) contextView.findViewById(R.id.name);
            contextNameView.setText(pathBuilder.getPath());
            taskContextContainer.addView(contextView);
         }
      }
   }
    
   @Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
    	Log.d(TAG, "Got resultCode " + resultCode + " with data " + data);
	}
        
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       Resources resources = getResources();
       menu.add(0, MENU_EDIT, 0, resources.getString(R.string.menu_edit))
          .setIcon(android.R.drawable.ic_menu_edit).setAlphabeticShortcut('e');
       menu.add(0, MENU_DELETE, 0, resources.getString(R.string.menu_delete))
          .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d');
       menu.add(0, MENU_MARK_COMPLETED, 0, resources.getString(R.string.menu_mark_completed))
          .setIcon(android.R.drawable.ic_menu_close_clear_cancel).setAlphabeticShortcut('c');
       menu.add(0, MENU_TIMER, 0, resources.getString(R.string.menu_timer))
          .setIcon(R.drawable.menu_timer).setAlphabeticShortcut('t');
       return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case MENU_EDIT:
          Intent intent = new Intent(Intent.ACTION_EDIT, itemUri);
          startActivityForResult(intent, ACTIVITY_EDIT_ACTION);
          break;
       case MENU_DELETE:
           askDeleteTask();
          break;
       case MENU_MARK_COMPLETED:
          if (originalTask.getNumberOfSubTasks() == null || originalTask.getNumberOfSubTasks() == 0) {
              markTaskCompleted(false);
          } else {
              askCompletedSubTasks();
          }
          break;
       case MENU_TIMER:
          showDialog(DIALOG_TIMER);
         break;
       }
       return super.onOptionsItemSelected(item);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
       Dialog dialog = null;
       switch (id) {
       case DIALOG_TIMER:
          TimerDialog timerDialog = new TimerDialog(this);
          timerDialog.setTask(originalTask);
          dialog = timerDialog;
          break;
       default:
          dialog = super.onCreateDialog(id);
          break;
       }
       return dialog;
    }

    private void markTaskCompleted(boolean markSubTasksCompleted) {
//        originalTask.setComplete(true);
        ContentValues values = new ContentValues();
        values.put(Task.Column.COMPLETE, 1);
//        originalTask.toValues(values);
        if (markSubTasksCompleted) {
            Uri taskAndSubTasks = ContentUris.withAppendedId(Task.ContentUri.TASK_AND_SUB_TASKS, (long) originalTask.getId());
            getContentResolver().update(taskAndSubTasks, values, null, null);
        } else {
            getContentResolver().update(itemUri, values, null, null);
        }
        finish();
    }
    
    private void askDeleteTask() {
        AlertDialog.Builder builder = new AlertDialog.Builder(TaskViewActivity.this);
        builder.setTitle(R.string.task_delete_alert_title).setMessage(R.string.task_delete_alert_message)
           .setIcon(android.R.drawable.ic_dialog_alert);
        builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
                  if (originalTask.getNumberOfSubTasks() == null || originalTask.getNumberOfSubTasks() == 0) {
                      getContentResolver().delete(itemUri, null, null);
                      finish();
                  } else {
                      askDeleteSubTasks();
                  }
              }
        });
        builder.setNegativeButton(R.string.alert_no, null);
        builder.show();
    }
    
    private void askDeleteSubTasks() {
        AlertDialog.Builder builder = new AlertDialog.Builder(TaskViewActivity.this);
        builder.setTitle(R.string.task_delete_alert_title).setMessage(R.string.task_delete_sub_tasks_alert_message)
           .setIcon(android.R.drawable.ic_dialog_alert);
        builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
                  Uri subItemUri = ContentUris.withAppendedId(Task.ContentUri.TASK_AND_SUB_TASKS, (long) originalTask.getId());
                  getContentResolver().delete(subItemUri, null, null);
                  finish();
              }
        });
        builder.setNegativeButton(R.string.alert_no,  new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                getContentResolver().delete(itemUri, null, null);
                finish();
            }
      });
        builder.show();
    }
    
    private void askCompletedSubTasks() {
        AlertDialog.Builder builder = new AlertDialog.Builder(TaskViewActivity.this);
        builder.setTitle(R.string.task_delete_alert_title).setMessage(R.string.task_completed_sub_tasks_alert_message)
           .setIcon(android.R.drawable.ic_dialog_alert);
        builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
                  markTaskCompleted(true);
                  finish();
              }
        });
        builder.setNegativeButton(R.string.alert_no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                markTaskCompleted(false);
                finish();
            }
      });
        builder.show();
    }
    
}
